package edu.ajou.scw;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class Friend
 */
@WebServlet("/Friend")
public class Friend extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Friend() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		String id = request.getParameter("id");
		String friend = request.getParameter("friend");
		
		DatabaseConnector conn = new DatabaseConnector();
		
		if (action == null)
			action = "get";
		
		JSONObject result = new JSONObject();
		JSONArray members = new JSONArray();
		
		if (action.equals("get"))
		{
			ArrayList<UserInfo> friendList = conn.getFriendList(id);
			
			if (friendList != null)
			{
				for (int i=0; i<friendList.size(); i++)
				{
					JSONObject person = new JSONObject();
					UserInfo user = friendList.get(i);
					
					person.put("id", user.getId());
					person.put("name", user.getName());
					person.put("email", user.getEmail());
					person.put("image", user.getImage());
					members.add(person);
				}
				
				result.put("members", members);
			}
		}
		else if (action.equals("add"))
		{
			String sql = String.format("insert into `friend` values (\"%s\", \"%s\")", id, friend); 
			int r = conn.query(sql);
			if (r == 1)
			{
				Log.d(id, "", id + " added " + friend + " to friends list.");
				result.put("result", "ok");
			}
			else
				result.put("result", "fail");
		}
		else if (action.equals("delete"))
		{
			String sql = String.format("delete from `friend` where `id`=\"%s\" and `friend_id`=\"%s\"", id, friend); 
			int r = conn.query(sql);
			if (r == 1)
			{
				Log.d(id, "", id + " removed " + friend + " from friends list.");
				result.put("result", "ok");
			}
			else
				result.put("result", "fail");
		}
		
		PrintWriter writer = response.getWriter();
		
		writer.write(result.toJSONString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
